package com.echo.code.thread.aqs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLockExam Created by baiyap on 2018/10/10.
 */
public class ReentrantLockExam {

  public static void main(String[] args) {
    ReentrantLock lock = new ReentrantLock();
    ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < 10; i++) {
      service.execute(() -> {
        try {
          System.out.println(Thread.currentThread().getName() + " ready to get lock");
          lock.lock();
          System.out.println(Thread.currentThread().getName() + " get the lock");
          for (int j = 0; j < 5; j++) {
            System.out.println(Thread.currentThread().getName() + " is running, number = " + j);
            TimeUnit.MILLISECONDS.sleep(500);
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          lock.unlock();
          System.out.println(Thread.currentThread().getName() + " unlock");
        }
      });
    }
    service.shutdown();
    try {
      service.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
    }
    System.out.println("exit.");
  }
}